﻿using Dapper;
using Himp.TaskScheduling.Hangfire.Jobs;
using Himp.TaskScheduling.Hangfire.Models;
using Microsoft.Extensions.Options;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace Himp.TaskScheduling.Hangfire
{
    /// <summary>
    /// 自动存样柜信息
    /// </summary>
    public class BoltInfo1Job : BaseBoltInfoJob, IHostedService
    {
        #region 字段

        private readonly ConnectionStringOption _connectionStrings;
        private ILogger<BoltInfo1Job> _logger;


        #endregion

        #region 方法

        public BoltInfo1Job(ILogger<BoltInfo1Job> logger
            , IOptions<ConnectionStringOption> connectionStrings)
        {
            _logger = logger;
            _connectionStrings = connectionStrings.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("--------启动:自动存样柜1信息同步--------");

            try
            {
                using (IDbConnection connection = new SqlConnection(_connectionStrings.SampleCabinet1))
                {
                    connection.Open();
                    var boltInfoList = connection.Query<BoltInfoView>(GET_BOLTINFOVIEW_SQL);

                    using (IDbConnection preConnection = new SqlConnection(_connectionStrings.KaiY_Preparation))
                    {
                        using (IDbConnection rlWebConnection = new SqlConnection(_connectionStrings.RL_Web))
                        {
                            var samplePreparationRecList = rlWebConnection.Query<SamplePreparationRec>(GET_SAMPLE_PREPARATION_REC_SQL); //制样结果

                            foreach (var item in boltInfoList)
                            {
                                int machineCode = 1;
                                var sampleCabinetConfigInfoRec = BoltInfoConvert(machineCode, item);
                                //获取制样重量和人员
                                var samplePreparationRec = samplePreparationRecList.FirstOrDefault(s => s.PackCode == sampleCabinetConfigInfoRec.CoalSampleCode);

                                if (samplePreparationRec != null)
                                {
                                    sampleCabinetConfigInfoRec.QualityIncoming = samplePreparationRec.SampleWeight;
                                    sampleCabinetConfigInfoRec.SampleCustodian = samplePreparationRec.UserName;
                                }

                                bool exists = await rlWebConnection.ExecuteScalarAsync<bool>(EXIST_FLAG_SQL,
                                      new { SamplePositionNum = item.Bolt_ID, SampleCabNum = machineCode });

                                if (!exists)
                                {
                                    var insertStas = await rlWebConnection.ExecuteAsync(INSERT_SAMPLECABINET_CONFIGINFO
                                        , sampleCabinetConfigInfoRec);
                                }
                                else
                                {
                                    var insertStas = await rlWebConnection.ExecuteAsync(UPDATE_SAMPLECABINET_CONFIGINFO
                                        , sampleCabinetConfigInfoRec);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError(exception: e, "异常:自动存样1柜信息同步");
            }

            _logger.LogInformation("--------完成:自动存样柜1信息同步--------");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        #endregion
    }
}
